package com.haoshuang.zhouzhoubang.ui.activity

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.RadioButton
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.github.gzuliyujiang.wheelpicker.BirthdayPicker
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityInviteMasterRecordBinding
import com.haoshuang.zhouzhoubang.databinding.ItemInvitationMasterRecordBinding
import com.haoshuang.zhouzhoubang.model.bean.SfBean2
import com.haoshuang.zhouzhoubang.ui.dialog.CustomPartShadowPopupView
import com.haoshuang.zhouzhoubang.ui.vm.InviteMasterRecordViewModel
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.makeramen.roundedimageview.RoundedImageView
import com.mufeng.libs.base.BaseBindingHolder
import com.mufeng.libs.base.BaseBindingQuickAdapter
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.visibleOrGone
import java.util.*


/**
 *  邀请师傅记录界面
 */
class InviteMasterRecordActivity : BaseVMActivity<InviteMasterRecordViewModel, ActivityInviteMasterRecordBinding>() {
    /** recycleview列表适配器 */

    private val mrvAdapter by lazy {
        object : BaseBindingQuickAdapter<SfBean2, ItemInvitationMasterRecordBinding>(mOrderList){


            override fun onBindViewHolder(
                holder: BaseBindingHolder,
                position: Int,
                item: SfBean2?
            ) {
                val rivUserAvatar = holder.getView<RoundedImageView>(R.id.rivUserAvatar)    //用户头像
                val tvType = holder.getView<TextView>(R.id.tvType)    //用户头像
                val divider = holder.getView<View>(R.id.divider)    //分割线
                divider.visibleOrGone(holder.layoutPosition != items.size-1) // 分割线
                holder.getView<TextView>(R.id.tvName).text=item?.nickname
                holder.getView<TextView>(R.id.create_time).text=item?.create_time
                tvType.setText(item?.is_master)
                if (item?.is_master=="已入驻"){
                    tvType.setTextColor(Color.parseColor("#00B7F5"))
                }else{
                    tvType.setTextColor(Color.parseColor("#01CAA8"))
                }
                item.apply {
                    Glide.with(context) //用户头像
                        .load(item?.avatar)
                        .placeholder(R.mipmap.default_image)
                        .error(R.drawable.ic_launcher_background)
                        .into(rivUserAvatar)
                }
            }
        }
    }
    lateinit var currentRadio:RadioButton //当前的标签选项
    var isRadioCheck = false //是否屏蔽radio改变的监听
    var filter_type="0"
    var start_date=""
    var end_date=""
    override fun initView(savedInstanceState: Bundle?) {
        val layoutManager = LinearLayoutManager(this)	// 创建布局管理者
        binding.apply {
            appBar.ivBack.clickWithTrigger { finish() }
            appBar.tvTitle.text = "邀请师傅记录"
            recyclerView.layoutManager = layoutManager	// 给recycleview设置布局管理者
            recyclerView.adapter = mrvAdapter	// 给recycleview设置适配器对象
            currentRadio = radioButton1
            radioGrop.setOnCheckedChangeListener { radioGroup, checkedId -> // 设置四个标签的选中事件改变时的监听
                /*由于点击自定义时间时会触发监听，因此在此处消耗一次需要*/
                if (isRadioCheck){
                    isRadioCheck = false
                    return@setOnCheckedChangeListener
                }else{
                    currentRadio = radioGroup.findViewById<RadioButton>(checkedId)

                    llCustomTime.setBackgroundResource(R.drawable.recatangle_f5_12dp)
                    tvCustomTime.setTextColor(resources.getColor(R.color.c_66))

                    start_date=""
                    end_date=""
                    when(radioGroup.findViewById<RadioButton>(checkedId)){
                        radioButton1 -> {
                            filter_type = "0"
                        }
                        radioButton2 -> {
                            filter_type = "1"
                        }
                        radioButton3 -> {
                            filter_type = "2"
                        }
                        radioButton4 -> {
                            filter_type= "3"
                        }
                    }

                    binding.refreshLayout.autoRefresh()
                }
            }

            llCustomTime.clickWithTrigger {
                XPopup.Builder(this@InviteMasterRecordActivity)
                    .atView(llLabRoot)
                    .isDestroyOnDismiss(false)
                    .setPopupCallback(object : SimpleCallback(){
                        override fun onCreated(popupView: BasePopupView?) {
                            super.onCreated(popupView)
                            // 弹窗内部onCreate执行完调用
                        }

                        override fun beforeShow(popupView: BasePopupView?) {
                            super.beforeShow(popupView)
                            //在每次show之前都会执行，可以用来进行多次的数据更新
                        }

                        override fun onShow(popupView: BasePopupView?) {
                            super.onShow(popupView)
                            // 完全显示的时候执行
                        }

                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
                            // 完全隐藏的时候执行
                        }

                        override fun beforeDismiss(popupView: BasePopupView?) {
                            super.beforeDismiss(popupView)
                            // 完全隐藏之前执行
                        }

                        //如果你自己想拦截返回按键事件，则重写这个方法，返回true即可
                        override fun onBackPressed(popupView: BasePopupView?): Boolean {
                            return super.onBackPressed(popupView)
                        }

                        //监听软键盘高度变化，高度为0说明软键盘关闭，反之则打开
                        override fun onKeyBoardStateChanged(
                            popupView: BasePopupView?,
                            height: Int
                        ) {
                            super.onKeyBoardStateChanged(popupView, height)
                        }

                        //监听弹窗拖拽，适用于能拖拽的弹窗
                        override fun onDrag(
                            popupView: BasePopupView?,
                            value: Int,
                            percent: Float,
                            upOrLeft: Boolean
                        ) {
                            super.onDrag(popupView, value, percent, upOrLeft)
                        }
                    })
                    .asCustom(
                        CustomPartShadowPopupView(this@InviteMasterRecordActivity, ::creatTimePicker,::onCancel){ starTime, endTime ->
                            isRadioCheck = true
                            radioButton1.isChecked = false
                            radioButton2.isChecked = false
                            radioButton2.isChecked = false
                            radioButton3.isChecked = false
                            radioButton4.isChecked = false
                            isRadioCheck = false

                            llCustomTime.setBackgroundResource(R.drawable.recatangle_00b7f5_12dp)
                            tvCustomTime.setTextColor(resources.getColor(R.color.c_3b76c2))

                            filter_type= "4"
                            start_date = starTime
                            end_date = endTime
                            binding.refreshLayout.autoRefresh()
                        }
                    )
                    .show()
            }
        }

        // 添加分割线
        //添加默认分割线
        /*val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        decoration.setDrawable(resources.getDrawable(R.drawable.shape_divider_c_f4_h_1dp))
        binding.recyclerView.addItemDecoration(decoration)*/


    }
    /**创建时间选择器 返回选择的时间格式”年-月-日“*/
    private fun creatTimePicker(it: TextView): String {
        var title = ""
        when(it.id){
            R.id.tvStartTime -> { title = "开始时间" }
            R.id.tvEndTime ->  { title = "结束时间" }
        }
        /*时间选择器需要用到的起止时间*/
        val calendar = Calendar.getInstance()
        var currentYear = calendar[Calendar.YEAR]
        var currentMonth = calendar[Calendar.MONTH] + 1
        var currentDay = calendar[Calendar.DAY_OF_MONTH]
        val startValue = DateEntity.target(currentYear - 100, 1, 1)
        val endValue = DateEntity.target(currentYear, currentMonth, currentDay)

        if (!it.text.isNullOrEmpty()){
            val l = it.text.split("-")
            currentYear = l.get(0).toInt()
            currentMonth = l.get(1).toInt()
            currentDay = l.get(2).toInt()
        }

        val picker = BirthdayPicker(this@InviteMasterRecordActivity)
        picker.setDefaultValue(currentYear, currentMonth, currentDay)   //设置默认值
        picker.wheelLayout.setRange(startValue, endValue)   // 设置起止时间
        picker.setTitle(title)   // 设置标题
        picker.setOnDatePickedListener { year, month, day ->
            (it as TextView).text = "$year-$month-$day"
        }
        picker.getWheelLayout().setResetWhenLinkage(false)
        picker.show()
        return "${(it as TextView).text}"
    }

    /**点击取消时*/
    private fun onCancel(){

    }
    override fun initData() {
        binding.refreshLayout.setOnLoadMoreListener {
            p++
            isShowing = false
            getNet()
        }

        binding.refreshLayout.setOnRefreshListener {
            p = 1
            isShowing = false
            getNet()
        }
        p = 1
        isShowing = false
        getNet()

    }


    private fun getNet() {
        if (filter_type=="4"){
            vm.getData("filter_type" to filter_type,"start_date" to start_date,
                "end_date" to end_date,"page" to p)
        }else{
            vm.getData("filter_type" to filter_type,"page" to p)
        }
    }
    private var mOrderList = mutableListOf<SfBean2>()
    override fun startObserve() {
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                binding.refreshLayout.finishRefresh()
                binding.refreshLayout.finishLoadMore()
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                binding.refreshLayout.finishLoadMore()
                if (p == 1) {
                    mOrderList.clear()
                }
                mOrderList.addAll(it!!)
                mrvAdapter.notifyDataSetChanged() // 适配器添加数据
            }
        }
    }

}